package com.zzyy.dtx.score.msg;

import com.alibaba.fastjson.JSON;
import com.zzyy.dtx.commons.enums.MsgEnum;
import com.zzyy.dtx.msg.api.MsgApi;
import com.zzyy.dtx.msg.dto.MsgDTO;
import com.zzyy.dtx.score.dto.ScoreDTO;
import com.zzyy.dtx.score.entities.ScoreAccount;
import com.zzyy.dtx.score.entities.ScoreDetail;
import com.zzyy.dtx.score.mapper.ScoreAccountMapper;
import com.zzyy.dtx.score.mapper.ScoreDetailMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@RabbitListener(bindings=@QueueBinding(
        value= @Queue(value="${mq.msg.queue.name}",autoDelete="false"),
        exchange=@Exchange(value="${mq.msg.exchange}",type= ExchangeTypes.DIRECT),
        key="${mq.msg.queue.routing.key}"
)
)
public class MsgHandler {

    @Resource
    private MsgApi msgApi;

    @Resource
    private ScoreAccountMapper scoreAccountMapper;
    @Resource
    private ScoreDetailMapper scoreDetailMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(MsgHandler.class);

    @RabbitHandler
    public void process(String content){
        ScoreDTO scoreDTO=JSON.parseObject(content,ScoreDTO.class);
        System.out.println("接收到积分:"+scoreDTO.getScore());

        //第二步：幂等性校验
        ScoreDetail scoreDetail=new ScoreDetail();
        scoreDetail.setOrderNo(scoreDTO.getOrderNo());
        ScoreDetail temp=this.scoreDetailMapper.selectOne(scoreDetail);
        if(temp!=null && temp.getType().intValue()==1){
            LOGGER.warn("送积分的订单号存在！"+temp.getOrderNo());
            //删除消息，
            //this.deleteMsg(scoreDTO);
            return ;
        }
        //对应设计图的步骤8
        //第三步：插入积分明细
        BeanUtils.copyProperties(scoreDTO,scoreDetail);
        //scoreDetail.setTxStatus(TccEnum.TRY.getCode());
        scoreDetail.setType((byte)1);
        this.scoreDetailMapper.insertSelective(scoreDetail);


        //第四步：新增积分
        ScoreAccount updateScoreAccount=new ScoreAccount();
        updateScoreAccount.setUserId(scoreDTO.getUserId());
        //积分处理
        updateScoreAccount.setTotalScore(scoreDTO.getScore());
        this.scoreAccountMapper.addScore(updateScoreAccount);


        //最后删除消息  对应设计图的步骤9
        //this.deleteMsg(scoreDTO);
    }

    private void deleteMsg(ScoreDTO scoreDTO){
        String msgid= MsgEnum.SCORE.getCode()+"-"+scoreDTO.getOrderNo();
        MsgDTO msgDTO=new MsgDTO();
        msgDTO.setMsgId(msgid);
        //this.msgApi.deleteMsg(msgDTO);
    }
}
